#include <cstdint>
#include <vector>
#include <map>
#include <string>


class UMode
{
public:
    using Candidates = std::vector<std::string>;
    struct WordNode 
    {
        std::map<char, WordNode> children;
        uint32_t freq; //词频：0~200, 0 means not a complete word
        WordNode() : freq(0) {} 
    };
public:
    UMode();
    void Init(); //load internal u-words
    //dict: file of words  
    int LoadDict(const std::string &dict); //可选
    const Candidates &Decode(const std::string &ustr);
    void Clear();
    //idx: begin at 0
    const std::string Select(int idx);
    const std::string &GetComposition(void) { return _prefix; }
    //设置最大候选个数
    void SetMaxCandidates(int cnt) { _max_cands = cnt; }
    //设置最小词频，词典中低于该词频的将被忽略
    void SetMinFrequence(uint32_t freq) { _min_freq = freq;}

private:
    void insert_cand(const std::string &cand, uint32_t freq);
    void insert_word(WordNode &node, const char *w, uint32_t freq);
    void search(const WordNode &node, std::string &w);
    void search(const WordNode &node, const char *p);
private:
    WordNode _root;
    std::string _prefix;   
    int _max_cands;
    uint32_t _min_freq;
    Candidates _cands;
    std::map<uint32_t, Candidates>_cands_map;
    int _cands_cnt;
    static std::pair<std::string, std::uint32_t> uwords[127];
};
